package conput;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

public class Client extends Thread {

    private final static int stringLength = 1;
    private final static double writeProbability = .1;
    private final Server server;
    private final Random rng = new Random();
    private final CountDownLatch startSignal;
    private final CountDownLatch doneSignal;
    private volatile int count;

    public Client(int operations, CountDownLatch startSignal, CountDownLatch doneSignal, Server server) {
        count = operations;
        this.startSignal = startSignal;
        this.doneSignal = doneSignal;
        this.server = server;
    }

    @Override
    public void run() {
        try {
            startSignal.await();
            while (!Thread.interrupted() && count-- > 0) {
                int posts = server.size.get();
                if (posts == 0 || rng.nextDouble() > writeProbability)
                    server.write(getRandomString(stringLength));
                else server.read(rng.nextInt(posts));
            }
            doneSignal.countDown();
        } catch (InterruptedException e) {
            return;
        }
    }

    private String getRandomString(int length) {
        return length == 0 ? "" : rng.nextInt(10) + getRandomString(length - 1);
    }
}
